import React, { Component } from 'react';
import {
  View,
  Text,
  Image,
  StyleSheet,
  TouchableOpacity,
  DeviceEventEmitter,
  Platform,
} from 'react-native';

import { TabNavigator } from 'react-navigation';
import _ from 'lodash';

import PxToDp from '../../../utils/PxToDp';
import FontFamilys from '../../../utils/FontFamilys';
import NavCon from '../../Public/NavCon';
import AddCarModel from '../../../containers/AddCarModelContainer';
import DynamicProperty from './DynamicProperty';
import SafetyProperty from './SafetyProperty';
import ComfortProperty from './ComfortProperty';
import EconomyProperty from './EconomyProperty';
import EntertainProperty from './EntertainProperty';


import { fetchCompareCars } from '../../../actions/communicateAction';

/* global ws */

const ComRoutes = {
  动力性: { screen: DynamicProperty },
  安全性: { screen: SafetyProperty },
  舒适性: { screen: ComfortProperty },
  经济性: { screen: EconomyProperty },
  娱乐性: { screen: EntertainProperty },
};

const ComTabConfig = {
  stateName: 'DynamicProperty',
  initialRouteName: '动力性',
  tabBarPosition: 'top',
  animationEnabled: false,
  swipeEnabled: true,
  tabBarOptions: {
    activeTintColor: '#333333', // 当前活动tab字体颜色
    inactiveTintColor: '#666',  // 默认字体颜色
    indicatorStyle: {  // 边框设置
      borderBottomColor: '#F65252',
      borderBottomWidth: 2,
    },
    scrollEnabled: true,
    showIcon: false,
    pressOpacity: 0.8,
    style: {
      height: 44,
      backgroundColor: '#fff',
      alignItems: 'center',
      justifyContent: 'center',
    },
    labelStyle: {
      fontSize: 14,
      fontFamily: FontFamilys(),
    },
    tabStyle: {
      width: PxToDp(100),
    },
  },
};
const PerformNavigation = TabNavigator(ComRoutes, ComTabConfig);


class CompetingModel extends Component {
  constructor(props) {
    super(props);

    this.state = {
      selectedTab: 'Event',
      itemIndex: 0,
      compareCar: '',
    };
  }

  _goBack() {
    this.props.navigator.pop();
  }

  _goAddCarModel() {
    const { navigator, carBrands, carInfo } = this.props;
    const { car } = carInfo;
    this.props.navigator.push({
      component: AddCarModel,
      passProps: {
        navigator,
        carBrands,
        car,
      },
    });
  }

  _sendMessage() {
    const { compare } = this.props;
    console.log('send compare: ', compare);
    if (ws) {
      ws.send(JSON.stringify({ compare: JSON.stringify(compare.compare) }));
      DeviceEventEmitter.emit('showToast', '竞品车型对比信息发送成功！');
    }
  }

  // 整理数据
  _cleanCompare(compare) {
    const $this = this;
    if (!compare) {
      return [];
    }
    const newArr = [];
    _.forIn(compare, (carsArr, title) => {
      const obj = {
        title,
        car1: [], // 看过的车型
        car2: [], // 选择的车型
      };
      if (carsArr.datas.length > 1) {
        obj.cars = 2;
        _.forIn(carsArr.datas[0], (car1) => {
          _.forIn(car1, (cardetail1) => {
            obj.car1.push({
              name: cardetail1.label,
              value: $this.parseCarValue(cardetail1.value),
              image: $this.getStrangeImage(cardetail1.value, 'car1'),
            });
          });
        });
        _.forIn(carsArr.datas[1], (car2) => {
          _.forIn(car2, (cardetail2) => {
            obj.car2.push({
              name: cardetail2.label,
              value: $this.parseCarValue(cardetail2.value),
              image: $this.getStrangeImage(cardetail2.value, 'car2'),
            });
          });
        });
        newArr.push(obj);
      } else if (carsArr.datas.length === 1) {
        obj.cars = 1;
        _.forIn(carsArr.datas[0], (car1) => {
          _.forIn(car1, (cardetail1) => {
            obj.car1.push({
              name: cardetail1.label,
              value: $this.parseCarValue(cardetail1.value),
              image: $this.getStrangeImage(cardetail1.value, 'car1'),
            });
          });
        });
        newArr.push(obj);
      }
    });
    return newArr;
  }

  getStrangeImage(value, car) {
    if (_.isEqual(value, '●')) {
      if (car === 'car1') {
        return require('../../../img/home/oCarredYes.png');
      }
      return require('../../../img/home/oCargreyYes.png');
    } else if (_.isEqual(value, '-')) {
      if (car === 'car1') {
        return require('../../../img/home/oCarredNo.png');
      }
      return require('../../../img/home/oCargreyNo.png');
    }
    return '';
  }

  parseCarValue(value) {
    return isNaN(value) ? value : +value;
  }

  componentDidMount() {
    const { carInfo, compareCar } = this.props;
    const ids = this.getCompareCarIds(carInfo.car, compareCar);
    const { dispatch } = this.props;

    dispatch(fetchCompareCars(ids));
  }

  getCompareCarIds(defaultCar, compareCar) {
    return compareCar && compareCar.id ?
    [].concat(defaultCar.id, compareCar.id) :
    [].concat(defaultCar.id);
  }

  render() {
    const { carInfo, compareCar, compare } = this.props;
    const { car, user } = carInfo;
    const compareDatas = this._cleanCompare(compare && compare.echarts);
    console.log('compare: ', compare);

    return (
      <View style={[styles.bgColor, styles.flex, styles.titleTop]}>
        <NavCon currentTitle="竞品车型" bgColor="#fff" onPress={() => this._goBack()} />
        <View style={[styles.row, styles.modelWrapper, { backgroundColor: 'transparent' }]}>
          <Text style={[styles.item]}>当前车型：</Text>
          <View style={[styles.icon, { backgroundColor: '#f15556' }]} />
          <Text style={[styles.model]}>{car ? car.modeldesc : ''}</Text>
        </View>
        <TouchableOpacity
          activeOpacity={0.6}

          style={[styles.row, styles.modelWrapper, { backgroundColor: '#fff', marginBottom: 10 }]}
          onPress={() => this._goAddCarModel()}
        >
          <Text style={[styles.item]}>对比车型：</Text>
          <View style={[styles.icon, { backgroundColor: '#c6ced9' }]} />
          {
            compareCar && compareCar.modeldesc ?
              <Text style={[styles.model, { fontSize: PxToDp(14), color: '#999' }]}>{ compareCar.modeldesc }</Text> :
              <Text style={[styles.model, { fontSize: PxToDp(14), color: '#999' }]}>请添加对比车型</Text>
          }
          <Image
            source={require('../../../img/right_arrow.png')}
            style={[styles.backIcon]}
          />
        </TouchableOpacity>
        <PerformNavigation
          screenProps={compareDatas}
          selected={this.state.selectedTab === 'Event'}
          itemIndex={this.state.itemIndex}
          onNavigationStateChange={(
              lastState, newState) => {
            this.setState({ itemIndex: newState.index });
          }
          }
        />
        <TouchableOpacity
          activeOpacity={0.6}
          style={[styles.submitWrapper]}
          onPress={() => this._sendMessage()}
        >
          <Text style={[styles.submit]}>发送至{user && user.username}</Text>
        </TouchableOpacity>
      </View>
    );
  }
 }

const styles = StyleSheet.create({
  bgColor: {
    justifyContent: 'space-between',
    backgroundColor: '#f8f8fb',
  },
  flex: {
    flex: 1,
  },
  row: {
    flexDirection: 'row',
  },
  modelWrapper: {
    alignItems: 'center',
    width: '100%',
    height: PxToDp(54),
    paddingLeft: PxToDp(10),
  },
  item: {
    color: '#333',
    fontSize: PxToDp(16),
  },
  icon: {
    width: PxToDp(16),
    height: PxToDp(16),
    marginLeft: PxToDp(0),
  },
  model: {
    flexWrap: 'wrap',
    width: PxToDp(228),
    marginLeft: PxToDp(10),
    color: '#333',
    fontSize: PxToDp(14),
  },
  backIcon: {
    width: PxToDp(8),
    height: PxToDp(16),
  },
  submitWrapper: {
    justifyContent: 'center',
    alignItems: 'center',
    width: '100%',
    height: PxToDp(44),
    backgroundColor: '#f15556',
  },
  submit: {
    color: '#fff',
    fontSize: PxToDp(16),
  },
  titleTop: {
    marginTop: Platform.OS === 'ios' ? 20 : 0,
  },
});

export default CompetingModel;
